﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Gman.Entity.Entities;
using Gman.WebApp.ServiceControllers;
using Gman.WebApp.Models;
using System.Web.Caching;
using Gman.WebApp.Controllers.Base;
using System.Web.UI;

using System.IO;

namespace Gman.WebApp.Controllers
{
    public class BienController : BaseController
    {
        private OperacionServiceController service = new OperacionServiceController();
        private IList<BienBE> lista = new List<BienBE>();

        private IFileStore _fileStore = new DiskFileStore(); //imagen

        //
        // GET: /Bien/Search   
        public ActionResult Search()
        {
            BienBE bien = new BienBE();
            var model = new BienModel(bien);

            model.Action = "search";
            model.ToolBar = new ToolBarModel();

            return View(@"~/Views/Bien/Edit.cshtml", model);
        }

        //
        // POST: /Bien/DoSearch   
        public ActionResult DoSearch(string cod)
        {
            var cache = new CacheProvider();

            BienBE obj = new BienBE();
            obj.CodBien = cod;

            var bien = service.ObtenerBien(obj);
            if (bien != null)
            {
                var model = new BienModel(bien);
                cache.Set(model.ID.Value.ToString(), model);
                model.Action = "query";
                model.ToolBar = new ToolBarModel();

                return View(@"~/Views/Bien/Edit.cshtml", model);
            }

            return AjaxResultSuccess(string.Format("No se encontró bien :{0} ", cod));
        }

        //
        // POST: /Bien/Edit
        public ActionResult Edit(string cod)
        {
            var cache = new CacheProvider();

            BienBE obj = new BienBE();
            obj.CodBien = cod;

            var bien = service.ObtenerBien(obj);

            if (bien != null)
            {
                var model = new BienModel(bien);
                cache.Set(model.ID.Value.ToString(), model);
                model.Action = "edit";
                model.ToolBar = new ToolBarModel();

                return View(@"~/Views/Bien/Edit.cshtml", model);
            }

            return RedirectToAction("Search");
        }

        //
        // GET: /Bien/Create   
        public ActionResult Create()
        {
            var cache = new CacheProvider();
            BienBE bien = new BienBE();

            var model = new BienModel(bien);
            cache.Set(model.ID.Value.ToString(), model);
            model.Action = "create";
            model.ToolBar = new ToolBarModel();

            return View(@"~/Views/Bien/Edit.cshtml", model);
        }

        //
        // GET: /Bien/Save           
        public JsonResult Save(Guid id, string action)
        {
            try
            {
                UsuariosBE user = (UsuariosBE)Session["user"];
                BienModel model = GetBienModel(id);
                
                if (action == "create")
                {                    
                    BienBE bien = new BienBE();
                    bien.IDEmp = user.IDEmp;

                    BienBE obj = new BienBE();
                    obj.CodBien = "BNR02013-" + (service.ListarBien(bien).Count + 1);
                    obj.TipoBien = model.Bien.TipoBien;
                    obj.NroSerieBien = model.Bien.NroSerieBien;
                    obj.DescBien = model.Bien.DescBien;
                    obj.IDSede = model.Bien.IDSede;
                    obj.AreaBien = model.Bien.AreaBien;
                    obj.LineaBien = model.Bien.LineaBien;
                    obj.GarantiaBien = model.Bien.GarantiaBien;
                    obj.IDProveedor = model.Bien.IDProveedor;
                    obj.TipoContratoBien = model.Bien.TipoContratoBien;
                    obj.NroGuiaRemiBien = model.Bien.NroGuiaRemiBien;
                    obj.VidaUtilBien = model.Bien.VidaUtilBien;
                    obj.FecCompBien = model.Bien.FecCompBien;
                    obj.CaractBien = model.Bien.CaractBien;
                    obj.FichaTecBien = model.Bien.FichaTecBien;
                    obj.UsuReg = user.NomUsu;
                    obj.FecReg = DateTime.Now;
                    obj.TermCnxReg = Environment.MachineName;
                    obj.EstadoBien = 1;
                    obj.IDEmp = user.IDEmp;

                    int resultado = service.RegistrarBien(obj);

                    if (resultado >= 1)
                    {
                        TempData["IDBien"] = resultado;

                        IList<String> listaImagen = new List<String>();
                        listaImagen.Add("C:/FILES");
                        listaImagen.Add("D:/GEMAN/FILES");
                        listaImagen.Add("D:/PROYECTO/FILES");

                        if (listaImagen.Count > 0)
                        {
                            ImagenBienBE imgBien = new ImagenBienBE();

                            for (int i = 0; i <= listaImagen.Count - 1; i++)
                            {
                                imgBien.IDBien = Convert.ToInt64(TempData["IDBien"]);
                                imgBien.RutaImg = listaImagen[i].ToString();

                                //int result = service.RegistrarImagenBien(imgBien);
                            }

                        }

                        return AjaxResultSuccess(string.Format("Bien {0} se guardo exitosamente.", obj.CodBien));
                    }
                    else
                    {
                        return AjaxResultSuccess(string.Format("No se guardo exitosamente."));
                    }
                }

                if (action == "edit")
                {
                    int resultado = service.ActualizarBien(model.Bien);

                    if (resultado == 1)
                    {
                        return AjaxResultSuccess(string.Format("Bien {0} se actualizo exitosamente.", model.Bien.CodBien));
                    }

                    else
                    {
                        return AjaxResultSuccess(string.Format("No se actualizo exitosamente."));
                    }
                }

                return AjaxResultSuccessNoParam();
            }
            catch (Exception ex)
            {
                return AjaxResultError(ex.Message);
            }
        }
        
        private IList<BienBE> ListaBien()
        {
            UsuariosBE user = (UsuariosBE)Session["user"];
            BienBE bien = new BienBE();
            bien.IDEmp = user.IDEmp;
            //lista = service.ListarBien(bien);
            return lista;
        }
                
        public BienModel GetBienModel(Guid id)
        {
            var cache = new CacheProvider();

            string key = id.ToString();
            var existingModel = cache.Get(key);
            if (existingModel == null)
            {
                existingModel = new BienModel(new BienBE());
                cache.Set(key, existingModel);
            }
            return (BienModel)existingModel;
        }

        public ActionResult UpdateField(string fieldName, string fieldValue, Guid id, string setterFormatOptions)
        {
            BienModel model = GetBienModel(id);
            SetterFormatOptions setterFormatOptionsEnum = SetterFormatOptionsHelper.Parse(setterFormatOptions);
            List<KeyValuePair<string, string>> validationList = new List<KeyValuePair<string, string>>();            

            var setter = new PropertySetter<BienBE>.SetterOptions();
            setter.objectToSet = model.Bien;
            setter.property = fieldName;
            setter.val = fieldValue;
            setter.SetterFormatOptions = setterFormatOptionsEnum;
            setter.validationList = validationList;

            object valueWasSet = PropertySetter<BienBE>.SetFinalObject(setter);


            validationList.AddRange(new BienModelValidator().Validate(model));

            return Json
                (new
                {
                    result = true,
                    PropertyValidationList = validationList,
                }
                );
        }

        public ActionResult GetValidation(Guid id)
        {
            BienModel model = GetBienModel(id);
            List<KeyValuePair<string, string>> validationList = new List<KeyValuePair<string, string>>();            

            validationList.AddRange(new BienModelValidator().Validate(model));

            return Json(new
            {
                PropertyValidationList = validationList                
            });
        }

        #region PruebaIMG

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult AjaxSubmit(int? id)
        {
            Session["ContentLength"] = Request.Files[0].ContentLength;
            Session["ContentType"] = Request.Files[0].ContentType;
            byte[] b = new byte[Request.Files[0].ContentLength];
            Request.Files[0].InputStream.Read(b, 0, Request.Files[0].ContentLength);
            Session["ContentStream"] = b;
            return Content(Request.Files[0].ContentType + ";" + Request.Files[0].ContentLength);
        }

        public ActionResult ImageLoad(int? id)
        {
            byte[] b = (byte[])Session["ContentStream"];
            int length = (int)Session["ContentLength"];
            string type = (string)Session["ContentType"];
            Response.Buffer = true;
            Response.Charset = "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = type;
            Response.BinaryWrite(b);
            Response.Flush();
            Response.End();
            Session["ContentLength"] = null;
            Session["ContentType"] = null;
            Session["ContentStream"] = null;
            return Content("");
        }

        #endregion

        public Guid AsyncUpload()
        {
            return _fileStore.SaveUploadedFile(Request.Files[0]);


        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Search(Guid? photo_guid, string photo_filename)
        {
            if (Request.Files["photo"] != null) // If uploaded synchronously
            {
                photo_guid = _fileStore.SaveUploadedFile(Request.Files["photo"]);
                photo_filename = Request.Files["photo"].FileName;
            }

            ViewData["photo_guid"] = photo_guid.Value;
            ViewData["photo_filename"] = photo_filename;

            var cache = new CacheProvider();
            BienBE bien = new BienBE();

            var model = new BienModel(bien);
            cache.Set(model.ID.Value.ToString(), model);
            model.Action = "Search";
            model.ToolBar = new ToolBarModel();

            return View(@"~/Views/Bien/Edit.cshtml", model);


        }
    }
}
